package network;

public class MessageTools {

	/**
	 * Convert the byte array to an int.
	 *
	 * @param b The byte array
	 * @return The integer
	 */ 
	public synchronized static final int byteArrayToInt(byte [] b) {
		int res=0;	
		res+=((b[0] & 0xFF) << 24);
		res+=((b[1] & 0xFF) << 16);
		res+=((b[2] & 0xFF) << 8);
		res+=b[3] & 0xFF;
		return res;
	}


	public synchronized static final byte[] intToByteArray(int value) {
		return new byte[] {
				(byte)(value >>> 24),
				(byte)(value >>> 16),
				(byte)(value >>> 8),
				(byte)value};
	}

	/**
	 * Convert a bytes array to booleans array.
	 * 
	 * @param bytes
	 *            The array to convert.
	 * @return A booleans array from bytes array.
	 */
	public synchronized static boolean[] bytes2booleans(byte[] bytes) {
		boolean[] booleans = new boolean[bytes.length * 8];
		for (int iByte = 0; iByte < bytes.length; iByte++) {
			for (int iBool = 1; iBool < 8; iBool++)
				booleans[iByte * 8 + iBool] = (bytes[iByte] & (byte) Math.pow(
						2, 8 - iBool - 1)) > 0 ? true : false;
						if (bytes[iByte] < 0)
							booleans[iByte * 8] = true;
						else
							booleans[iByte * 8] = false;
		}
		return booleans;
	}

	/**
	 * Convert a booleans array to bytes array.
	 * 
	 * @param booleans
	 *            The array to convert.
	 * @return A bytes array from booleans array.
	 */
	public synchronized static byte[] booleans2bytes(boolean[] booleans) {
		byte[] bytes;
		if(booleans.length % 8>0)
			bytes = new byte[(booleans.length / 8)+1];
		else
			bytes = new byte[booleans.length / 8];


		for (int iB = 0; iB < bytes.length; iB++) {
			byte B = 0;
			for (int i = 1; i < 8; i++) {
				int bToi;
				if(iB * 8 + i < booleans.length)
					bToi = booleans[iB * 8 + i] ? 1 : 0;
				else 
					bToi = 0;
				B += (byte) (Math.abs(bToi * Math.pow(2, 8 - i - 1)));
			}
			if (booleans[iB * 8])
				bytes[iB] = (byte) (128 + B);
			else
				bytes[iB] = B;
		}
		return bytes;
	}

}
